﻿using Microsoft.Extensions.Options;
using Microsoft.IdentityModel.Tokens;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;
using Volo.Abp.Timing;

namespace Loong.Admin.Security.Authentication.JwtBearer
{
    public class JwtHandler
    {
        private readonly JwtOptions _jwtOptions;
        private readonly IClock _clock;

        public JwtHandler(
            IOptions<JwtOptions> jwtOptionsAccessor,
            IClock clock)
        {
            _jwtOptions=jwtOptionsAccessor.Value;
            _clock=clock;
        }

        public string CreateJwtToken(ClaimsIdentity user)
        {
            var securityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_jwtOptions.Key));
            var credentials = new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256);

            var token = new JwtSecurityToken(
                issuer: _jwtOptions.Issuer,
                audience: _jwtOptions.Audience,
                expires: _clock.Now.AddMinutes(_jwtOptions.ValidMinutes),
                signingCredentials: credentials,
                claims: user.Claims
            );

            return new JwtSecurityTokenHandler().WriteToken(token);
        }
    }
}
